<template>
  <div class="refine_userlist applyUser_box">
    <h2 class="titleblue">申报用户列表</h2>
    <div class="contant">
      <div class="user-title">
        <div @click="createUser" class="fl create" v-if='showCreateBtn'>新建用户</div>
        <div class="fr">
          <el-input prefix-icon="el-icon-search" placeholder="搜索用户" v-model="keyword" class="plansearch" clearable
                    @change='search'>
            <template slot="append">搜索</template>
          </el-input>
        </div>
      </div>
      <data-table :page='currentPage' :head="thead" :data="tableData" :actions="['edit']"
                  @callback="dataAction"></data-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        layout="total,prev, pager, next, jumper"
        :total="dataCount"
        background
      >
      </el-pagination>
    </div>
    <el-dialog title="" :visible.sync="showCreateDialog" width="520px"
               append-to-body @close='closeDialog' @open='showCreateDialog = true'>
      <div class="refine_ucreate applyUser_box">
        <h2 class="titleblue">{{title}}用户</h2>
        <div class="contant" style="padding-bottom: 20px;">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="applyUser">
              <el-input v-model="ruleForm.applyUser" class="form--item"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" style="margin-bottom: 10px">
              <el-input type="password" v-model="ruleForm.password" class="form--item"></el-input>
            </el-form-item>
            <div class="input_span">
              <label style="color: #666;">强度:</label>
              <span id="one"></span>
              <span id="two"></span>
              <span id="three"></span>
            </div>
            <el-form-item label="姓名" prop="applyUserName">
              <el-input v-model="ruleForm.applyUserName" class="form--item"></el-input>
            </el-form-item>
            <el-form-item label="公司名" prop="applyUnit">
              <el-input v-model="ruleForm.applyUnit" class="form--item"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import DataTable from '@/components/common/DataTable.vue'
  import * as sysUserService from '@/services/SysUserService.js'
  import * as applyUsersService from '@/services/ApplyUsersService.js'
  const DEFAULT_PWD = '123qwe!@#QWE'

  export default {
    name: 'ApplyUser',
    components: {
      'data-table': DataTable
    },
    data: function () {
      return {
        keyword: '',
        editMode: false,
        thead: [
          {name: '用户名', prop: 'applyUser'},
          {name: '姓名', prop: 'applyUserName'},
          {name: '单位', prop: 'applyUnit'}
        ],
        tableData: [],
        currentPage: 1,
        currentPages: 1,
        dataCount: 0,
        showCreateDialog: false,
        showCreateBtn: true,
        title: '新增',
        ruleForm: {
          applyUser: '',
          password: '',
          applyUserName: '',
          applyUnit: ''
        },
        rules: {
          applyUser: [
            {required: true, validator: this.validateApplyUser, message: '请输入用户名', trigger: 'change'}
          ],
          // password: [
          //   {required: true, validator: this.validatePassword, message: '请输入密码', trigger: 'change'}
          // ],
          applyUserName: [
            {required: true, validator: this.validateApplyUserName, message: '请输入姓名', trigger: 'change'}
          ],
          applyUnit: [
            {required: true, validator: this.validateApplyUnit, message: '请输入公司名', trigger: 'change'}
          ]
        },
        passwordSt: '',
        msgText: 0
      }
    },
    created() {
      this.getData(0)
    },
    methods: {
      checkStrong(sValue) {
        var modes = 0;
        var str = sValue
        if (sValue.indexOf(' ') >= 0) {
          str = sValue.substring(0, sValue.indexOf(' '));
          this.form.newpwd = str;
        }
        //正则表达式验证符合要求的
        if (str.length < 1) return modes;
        if (/\d/.test(str)) modes++; //数字
        if (/[a-z]/.test(str)) modes++; //小写
        if (/[A-Z]/.test(str)) modes++; //大写
        if (/\W/.test(str)) modes++; //特殊字符
        //逻辑处理
        if (sValue.length >= 8 && modes > 1) {
          modes++
        }
        return modes;
      },
      getData(page) {
        let str = `applyUser=like=${this.keyword}`
        applyUsersService.getApplyUserList(str, page).then(res => {
          console.log(res)
          this.tableData = res.data
          this.dataCount = parseInt(res.headers['x-total-count'], 10)
        })
      },
      submitForm(formName) {
        if (!this.ruleForm.password) {
          this.ruleForm.password = DEFAULT_PWD
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.checkStrong(this.ruleForm.password) !== 5) {
              this.$message.warning('密码必须包含大小写字母+数字+特殊字符!')
              return
            }
            // if (this.msgText != 5) {
            //   this.$message({
            //     message: '密码必须包含大小写字母+数字+特殊字符!',
            //     type: 'warning'
            //   })
            //   return false
            // }
            if (this.editMode) {
              applyUsersService.updateApplyUser(this.ruleForm).then(res => {
                this.$message.success('修改成功！')
                this.closeDialog()
                this.getData(0)
              })
            } else {
              applyUsersService.createApplyUser(this.ruleForm).then(res => {
                this.$message.success('创建成功！')
                this.closeDialog()
                this.getData(0)
              })
            }
          }
        })
      },
      validateApplyUser(rule, value, callback) {
        if (value.trim() === '') {
          callback(new Error('用户名不能为空！'));
        } else {
          callback();
        }
      },
      validatePassword(rule, value, callback) {
        if (value.trim() === '') {
          callback(new Error('密码不能为空！'));
        } else {
          callback();
        }
      },
      validateApplyUserName(rule, value, callback) {
        if (value.trim() === '') {
          callback(new Error('姓名不能为空！'));
        } else {
          callback();
        }
      },
      validateApplyUnit(rule, value, callback) {
        if (value.trim() === '') {
          callback(new Error('公司名不能为空！'));
        } else {
          callback();
        }
      },
      search() {
        this.currentPage = 1
        this.getData(0)
      },
      dataAction(param) {
        if (param.action === 'edit') {
          this.editMode = true
          this.title = '修改'
          this.showCreateDialog = true
          param.data.password = ''
          this.ruleForm = param.data
        } else if (param.action === 'status') {
          let data = param.data
          data.status = data.status === 0 ? 1 : 0
          sysUserService.update(data).then(r => {
            this.$alert(data.status === 0 ? '启用成功' : '禁用成功').then(() => {
              this.getAll()
            })
          })
        } else if (param.action === 'del') {
          sysUserService.del(param.data.id).then(r => {
            this.$alert('删除成功').then(() => {
              this.getAll()
            })
          })
        } else if (param.action === 'reset') {
          this.$confirm('此操作将永久重置该用户密码, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sysUserService.resetPassword(param.data.id).then(res => {
              this.$alert('重置成功').then(() => {
                this.getAll()
              })
            })
          })
        }
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getData(val - 1)
      },
      closeDialog() {
        this.showCreateDialog = false
        setTimeout(() => {
          this.ruleForm = {
            applyUser: '',
            password: '',
            applyUserName: '',
            applyUnit: ''
          }
        }, 400)
      },
      createUser() {
        this.editMode = false
        if (this.$refs['ruleForm']) {
          this.$refs['ruleForm'].clearValidate()
        }
        this.showCreateDialog = true
      },
    },
    watch: {
      'ruleForm.password'(newname, oldname) {
        this.msgText = this.checkStrong(newname);
        if (this.msgText > 1 || this.msgText == 1) {
          document.getElementById('one').style.background = 'red';
          this.passwordSt = '弱'
        } else {
          document.getElementById('one').style.background = '#eee';
          this.passwordSt = '空'
        }
        if (this.msgText > 4 || this.msgText == 4) {
          document.getElementById('two').style.background = 'orange';
          this.passwordSt = '一般'
        } else {
          document.getElementById('two').style.background = '#eee';
          this.passwordSt = '空'
        }
        if (this.msgText == 5) {
          document.getElementById('three').style.background = '#00D1B2';
          this.passwordSt = '强'
        } else {
          document.getElementById('three').style.background = '#eee';
          this.passwordSt = '空'
        }
      }
    }
  }
</script>

<style lang='scss'>
  .refine_userlist {
    width: 100%;
    display: inline-block;

    .inlanselect {
      float: left;
      margin-right: 10px;
    }

    .el-tabs {
      width: 100%;
      margin-top: 20px;
      display: inline-block;
    }

    .el-table tr:nth-child(2n) {
      background: #FAFAFA
    }

    .table {
      margin-top: 20px;
    }

    .user-title {
      width: 100%;
      display: inline-block;
    }
  }

  .form--item {
    width: 300px;
  }

  .applyUser_box .el-form-item__error {
    position: relative !important;
  }
</style>

<style scoped>
  .input_span {
    padding-left: 100px;
    margin-bottom: 10px;
  }

  .input_span span {
    display: inline-block;
    width: 85px;
    height: 10px;
    background: #eee;
    line-height: 20px;
  }

  #one {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    border-right: 0px solid;
    margin-left: 6px;
    margin-right: 3px;
  }

  #two {
    border-left: 0px solid;
    border-right: 0px solid;
    margin-left: -5px;
    margin-right: 3px;
  }

  #three {
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    border-left: 0px solid;
    margin-left: -5px;
  }

  #font span:nth-child(1) {
    color: red;
    margin-left: 80px;
  }

  #font span:nth-child(2) {
    color: orange;
    margin: 0 60px;
  }

  #font span:nth-child(3) {
    color: #00d1b2;
  }
</style>
